package com.zl.learning.io.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhaolei on 2017/3/9.
 */
public class PackageRead2 {
    public static void main(String[] args) {
        List<String> classNames = getClassName("com.zl.util");
        for (String s : classNames) {
            System.out.println(s);
            try {
                Class c = Class.forName(s);
                Method[] methods = c.getMethods();
                for (Method m :methods){
                    System.out.println(m.toString());
                }
                System.out.println("------------------------------------------------------------------");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<String> getClassName(String packageName) {
        packageName = packageName.replace(".", File.separator);
        String filePath = null;
        try {
            filePath = URLDecoder.decode(ClassLoader.getSystemResource("").getPath() + packageName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return getClassName(filePath, null, packageName);
    }


    private static List<String> getClassName(String filePath, List<String> className, String packageName) {
        List<String> myClassName = new ArrayList<>();
        File file = new File(filePath);
        File[] childFiles = file.listFiles();
        assert childFiles != null;
        for (File childFile : childFiles) {
            if (childFile.isDirectory()) {
                myClassName.addAll(getClassName(childFile.getPath(), myClassName, packageName));
            } else {
                String childFilePath = childFile.getPath();
                childFilePath = childFilePath.substring(childFilePath.indexOf(packageName), childFilePath.lastIndexOf("."));
                childFilePath = childFilePath.replace(File.separator, ".");
                myClassName.add(childFilePath);
            }
        }
        return myClassName;
    }
}
